﻿#if XML
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;

namespace System {
	class PackageXml : PackageUnit,IXmlSerializable {
		#region Const
		public const String XmlRootName = "Root";
		public const String XmlTypeName = "Type";
		#endregion
		#region Public

		#endregion
		#region Public
		public Xml.Schema.XmlSchema GetSchema() {
			return new Xml.Schema.XmlSchema(){
				
			};
		}
		public void ReadXml(XmlReader reader) {
			throw new NotImplementedException();
		}
		public void WriteXml(XmlWriter writer) {
			if (writer.WriteState == WriteState.Start) {
				writer.WriteStartDocument();
				writer.WriteStartElement(XmlRootName);
				writer.WriteAttributeString(XmlTypeName, this.GetType().FullName);

				this.WriteXml(writer);

				writer.WriteEndElement();
				writer.WriteEndDocument();
			} else if (writer.WriteState == WriteState.Element){
				foreach (KeyValuePair<PackageProperty, Object> pair in this) {
					//Check if it's PackageUnit
					if (pair.Key.PropertyType.IsSubclassOf(typeof(PackageXml))) {
						PackageXml unit = (PackageXml)pair.Value;

						writer.WriteStartElement(pair.Key.Name);
						writer.WriteAttributeString(XmlTypeName, pair.Key.PropertyType.FullName);

						unit.WriteXml(writer);

						writer.WriteEndElement();
					} else {
						try {
							String value = Convert.ToString(pair.Value);

							//Success
							writer.WriteStartElement(pair.Key.Name);
							writer.WriteAttributeString(XmlTypeName,pair.Key.PropertyType.FullName);
							
							writer.WriteValue(value);
							writer.WriteEndElement();
						} catch {

						}
					}
				}
			}
		}
		public void WriteXml(Stream stream) {
			XmlWriterSettings config = new XmlWriterSettings() {
				Indent = true,
				NewLineHandling = NewLineHandling.Entitize,
				OmitXmlDeclaration = true,
				
			};
			this.WriteXml(stream, config);
		}
		public void WriteXml(Stream stream,XmlWriterSettings config) {
			using (XmlWriter writer = XmlWriter.Create(stream,config)) {
				this.WriteXml(writer);
			}
		}
		public void WriteXml(String path) {
			using (FileStream fs = File.OpenWrite(path)) {
				WriteXml(fs);
			}
		}
		#endregion
	}
}
#endif